#!/usr/bin/perl
# 2012/10/17 Output location of target sequence

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);

if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [input folder] -t [recognition sequence]\n";
}

my %opt;
getopts("i:t:", \%opt);
my $Dir = $opt{i};
my $recognitionSeq = $opt{t};
$recognitionSeq = uc($recognitionSeq);

print "number\tchr\tposition\tlength_before\tlength_after\n";
foreach my $chr(qw(chr1 chr2 chr3)){
	my $file = $Dir . $chr . '.fa';
	my $fh = IO::File->new($file) or die "cannot open $file: $!";
	my $seq = '';
	$fh->getline();
	while($_ = $fh->getline()){
		s/\r?\n//;
		$seq .= $_;
	}
	$seq = uc($seq);


	my $frag_number = 0;
	if($chr eq 'chr1'){
		$frag_number += 100000;
	}elsif($chr eq 'chr2'){
		$frag_number += 200000;
	}elsif($chr eq 'chr3'){
		$frag_number += 300000;
	}

	my $pos = 0;
	my $previous = 0;
	my @locationList;
	while($pos != -1){
		$pos = index $seq, $recognitionSeq, $previous;
		if($pos != -1){
			push @locationList, $pos;
		}
		$previous = $pos + 1;
	}
	my $totalLength = length $seq;
	push @locationList, $totalLength;

	# 最初と最後は、切断位置ではなくて、端を意味するだけなので飛ばす
	for(my $i = 1; $i < @locationList - 1; $i++){
		$frag_number++;
		my $length_before = $locationList[$i] - $locationList[$i-1];
		my $length_after = $locationList[$i+1] - $locationList[$i];
		print "$frag_number\t$chr\t$locationList[$i]\t$length_before\t$length_after\n";
	}
	$fh->close();
}

